# -*- coding: utf-8 -*-
# 创建时间：2021/8/10 14:22
from bs4 import BeautifulSoup
import requests
import time, math, random, json
import pymysql
import re
from xlwt import Workbook
from hhy import FileUtil, DateUtil, ToolUtil, HttpUtil
from hashlib import md5

__author__ = 'LuckyHhy'


def get_content():
    url = 'https://www.qtx.com/dbsoccer'
    headers = {"User-Agent": HttpUtil.AgentRandom()}
    A = requests.session()  # 用一个会话请求
    A.headers = headers
    cont = A.get(url, timeout=20, allow_redirects=False)
    soup = BeautifulSoup(cont.text, 'html.parser')
    item_all = soup.find(class_="switchItem").find_all(class_="item")
    data = []
    # print(item_all)
    for item in item_all:
        dataCountry = item.find_all(class_="dataCountry")
        # print(dataCountry[1])
        country_name = dataCountry[1].find(class_="tc_country_game").find_all(class_="country_name")
        # print(country_name)
        # 各个国家赛事
        for country in country_name:
            cuy = country.select("a")[0].get_text()  # 国家
            print("正在查找{0}国家的赛事".format(cuy))
            # print(cuy)
            country_detail = country.find(class_="country_detail").select("div")  # 各个赛事
            # print(country_detail)
            for detail in country_detail:
                schedule = detail.get_text()
                bra=trans(schedule)
                ck = [schedule,bra, cuy]
                data.append(ck)
                #一秒后请求
                time.sleep(1)
            print("{0}国家的赛事爬取完成".format(cuy))

    return data



# 保存到excel 文件
def save_xls(pathh):
    w = Workbook()
    ws = w.add_sheet('datas')  # 创建一个工作表

    results = get_content()
    i = 0
    for row in results:
        g = 0
        # print(f"正在执行第{i}行数据")
        for jj in row:
            ws.write(i, g, jj)  # 行 ，列  数据
            g = g + 1
        i = i + 1

    print("已经跳出来了")
    w.save(pathh)


def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()


#百度翻译
def trans(query):
    # Set your own appid/appkey.
    appid = '20191024000344032'
    appkey = '1qpPtPqQAcu3xLwUzJSV'

    from_lang = 'zh'
    to_lang = 'pt'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    if result['trans_result']:
        return result['trans_result'][0]['dst']

    return query

    # Show response
    #resultt=json.dumps(result, indent=4, ensure_ascii=False)
    #print(resultt)


def main():
    pathh = '各国赛事.xls'  # 存放路径
    save_xls(pathh)
    print("下载结束")
    pass


if __name__ == '__main__':
    main()
